// 导入express模块
let express = require('express')
// 创建一个路由
let router = express.Router()
// 导入封装好的db文件
let db = require('./../utils/db')




// 1.查询所有文章类别
router.get('/admin/category/list', function (req, res) {
    db('select * from categories', function (err, result) {
        if (err) return res.send({ code: 400, msg: '参数有误' })
        res.send(result)
    })
})

// 2.新增文章类别
router.post('/admin/category/add', function (req, res) {
    // 获取req传过来的name和slug
    let { name, slug } = req.body

    db(`INSERT INTO categories set name='${name}',slug='${slug}'`, function (err, result) {
        if (err || result.affectRows == 0) return res.send('参数错误')
        res.send({ code: 200, msg: '新增成功' })
    })
})

// 3.根据id查询指定文章类别
router.get('/admin/category/search', function (req, res) {
    // 获取id
    let { id } = req.query

    db(`select * from categories where id=${id}`, function (err, result) {
        if (err || result.length == 0) return res.send({ code: 400, msg: 'id参数有误' })
        res.send({ code: 200, msg: '查询成功' })
    })
})

// 4.编辑文章类别
router.post('/admin/category/edit', function (req, res) {
    // 获取id name slug
    let { id, name, slug } = req.body

    db(`update categories set name='${name}' ,slug='${slug}' where  id=${id}`, function (err, result) {
        if (err || result.affectRows == 0) return res.send({ code: 400, msg: '参数有误' })
        res.send({ code: 200, msg: '编辑成功' })
    })
})

// 5.删除文章类别
router.post('/admin/category/delete', function (req, res) {
    // 获取id
    let { id } = req.body

    db(`DELETE FROM categories WHERE id=${id};`, function (err, result) {
        if (err || result.affectRows == 0) return res.send({ code: 400, msg: '参数有误' })
        res.send({ code: 200, msg: '删除成功' })
    })
})


// 导出
module.exports = router